package maxssina.activity;

import java.util.Calendar;
import java.util.HashMap;

import maxssina.app.APP;
import maxssina.models.BaseResponse;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;

public class BaseActivity extends Activity 
{
	public APP mApp;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp=((APP)getApplicationContext());
	}

	@SuppressWarnings("unchecked")
		private HashMap<Long, AsyncWorker> Jobs = new HashMap<Long, AsyncWorker>();


	public <T extends BaseResponse> void startAsyncJob(AsyncJob<T> job) {
			long key = Calendar.getInstance().getTimeInMillis();
			AsyncWorker<T> task = new AsyncWorker<T>(key, job);
			Jobs.put(key, task);
			task.execute();
		}

		public <T extends BaseResponse> void cancelJobs() {
			for (AsyncWorker<T> job : Jobs.values()) {
				job.cancel(job.Interrupt);
			}
		}

		public abstract class AsyncJob<T extends BaseResponse> {
			private boolean Interrupt;

			public AsyncJob(boolean interrupt) {
				Interrupt = interrupt;
			}

			public boolean interrupt() {
				return Interrupt;
			}

			public abstract void preExecute();

			public abstract T start();

			public abstract void onSuccess(T response);

			public abstract void onError(T response);
		}

		private class AsyncWorker<T extends BaseResponse> extends
				AsyncTask<Void, Void, T> {

			public AsyncJob<T> Job;
			public long Key;
			public boolean Interrupt;

			public AsyncWorker(long key, AsyncJob<T> job) {
				Job = job;
				Key = key;
				Interrupt = job.Interrupt;
			}

			@Override
			protected void onPreExecute() {
				Job.preExecute();
			}

			@Override
			protected T doInBackground(Void... arg0) {
				return Job.start();
			}

			@Override
			protected void onPostExecute(T result) {
				if (result.Success) {
					Job.onSuccess(result);
				} else {
					Job.onError(result);
				}
				Jobs.remove(Key);
			}

		}
}
